package com.yu.blog.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yu.blog.entities.entity.Blog;
import com.yu.blog.result.Result;
import com.yu.blog.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/api")
public class BlogController {

    @Autowired
    private BlogService blogService;

    @GetMapping("/blogs")
    public Result<IPage<Blog>> queryAllBlog(@RequestParam(defaultValue = "1") Integer currentPage) {
        Page<Blog> page = new Page<>(currentPage, 7);
        IPage<Blog> pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("create_time"));
        return Result.success(pageData);
    }

    @GetMapping("/blog/{id}")
    public Result<Blog> detail(@PathVariable(name = "id") String id) {
        Blog blog = blogService.getById(id);
        Assert.notNull(blog, "该博客已被删除");
        return Result.success(blog);
    }

    @PreAuthorize("hasAnyRole('system')")
    @PostMapping("/blog/editOrUpdate")
    public Result<Blog> edit(@Validated @RequestBody Blog blog) {
        if ("0".equals(blog.getId())) {
            Blog saveBlog = new Blog();
            saveBlog.setTitle(blog.getTitle()).setContent(blog.getContent()).setDescription(blog.getDescription());
            return blogService.save(saveBlog) ? Result.success() : Result.failed();
        } else {
            Blog saveBlog = blogService.getById(blog);
            saveBlog.setTitle(blog.getTitle()).setContent(blog.getContent()).setDescription(blog.getDescription());
            return blogService.updateById(saveBlog) ? Result.success() : Result.failed();
        }
    }

    @PreAuthorize("hasAnyRole('system')")
    @DeleteMapping("/deleteBlog/{id}")
    public Result<Blog> deleteBlog(@PathVariable(name = "id") String id) {
        return blogService.removeById(id) ? Result.success() : Result.failed();
    }


}
